/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.common.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;

import com.pmc.dwa.common.exception.PmcRuntimeException;

/**
 * @description 工具类
 * @author aokunsang
 * @date 2013-1-9
 */
public class Util {

	/**
	 * 分离出有效字符(适用于RolelogController:getAllOperLog)
	 * @param source
	 * @param refer
	 * @return
	 */
	public static String separateValidWord(String source,String refer){
		String[] sourceSplit = source.split("\\|");
		for(String str : sourceSplit){
			String one = str.split("-")[0];
			String two = str.split("-")[1];
			if(one.equals(refer)){
				return two;
			}
			//System.out.println(str);
		}
		return "";
	}
	
	/**
	 * 获取当前用户的ip地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) {
       String ip = request.getHeader("x-forwarded-for");
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("Proxy-Client-IP");
       }
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getHeader("WL-Proxy-Client-IP");
       }
       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
           ip = request.getRemoteAddr();
       }
       if(ip.equals("0:0:0:0:0:0:0:1")){
    	   ip = "127.0.0.1";	//localhost ipv6->ipv4
       }
       return ip;
	}
	/**
	 * 分割插入、修改的sql语句
	 * @param sql
	 * @param columnMaps   <属性名,数据库中字段名>
	 * @return
	 */
	public static Map<String,List<String>> spQuerysql(String sql,Map<String,String> columnMaps){
		if(StringUtils.isEmpty(sql)) return null;
		String _sql = sql + " ";
		String key = _sql.replaceAll(":(.+?),\\s*", "?,").replaceAll(":(.+?)[)]\\s*", "?)").replaceAll(":(.+?)\\s+", "? ");
		Map<String,List<String>> result = new HashMap<String, List<String>>();
		List<String> fieldList = new LinkedList<String>();
		Pattern pattern = Pattern.compile(":(.+?)[)|,|\\s*]");
		Matcher matcher = pattern.matcher(_sql);
		StringBuffer insertString = new StringBuffer();
		while(matcher.find()){
			String value = matcher.group(1);
			fieldList.add(value);
			insertString.append(columnMaps.get(value)+ ",");
		}
		if(fieldList.isEmpty() || key.equals(_sql)) return null;
		StringBuffer key_sb = new StringBuffer(key);
		if(!key.trim().matches("insert\\s*into\\s*[\\w|_]+?\\(.*?\\)\\s*values.*") && !key.trim().contains("update")){  //判断insert语句是否有数据库字段，比如：insert into t1(ID,NAME) 
			key_sb.insert(key_sb.indexOf("values")-1, "("+insertString.substring(0,insertString.length()-1)+")");
		}
		result.put(key_sb.toString(), fieldList);
		return result;
	}
	/**
	 * 通过查询语句分离出相应信息
	 * @param sql
	 * @param clazz
	 * @return
	 */
	public static Field[] spSelectSql(String sql,Class<?> clazz){
		if(StringUtils.isEmpty(sql) || sql.indexOf("*")!=-1) return null;
		Map<String,Field> fieldMap = new HashMap<String,Field>();
		List<Field> list = new ArrayList<Field>();
		Field[] fields = clazz.getDeclaredFields();   //获取所有属性
		for(Field field : fields){
			fieldMap.put(BeanUtils.getPmcColumnName(field), field);
		}
		String[] columnNameArry = sql.substring(sql.toLowerCase().indexOf("select") + 6,sql.toLowerCase().indexOf("from")).replaceAll("\\s", "").split(",");
		for(String columnName : columnNameArry){
			if(columnName.indexOf(".") != -1){
				columnName = columnName.substring(columnName.indexOf(".")+1).trim();
			}else{
				columnName = columnName.trim();
			}
			Field field = fieldMap.get(columnName);
			if(field==null) throw new PmcRuntimeException(String.format("你提供的SQL语句中的数据库字段[%s]，没有在Bean中找到有效的属性值对应。", columnName));
			list.add(field);
		}
		return list!=null ? list.toArray(new Field[]{}) : null;
	}
}
